const Banner = tableMap.get("banner");

function formatBanner(form) {
	const title = String.asString(form.title).trim();
	const description = String.asString(form.description).trim();
	const url = String.asString(form.url).trim();
	const html = String.asString(form.html).trim();

	const createTime = +form.createTime || Date.now();
	if (!html && !url) {
		Throw("ref", "横幅的图片地址不可为空")
	}
	if (url && !$$.isUrl(url)) {
		Throw("syntax", "横幅的图片地址有误，请使用正确的图片链接")
	}
	return {
		title: title,
		description: description,
		url: url,
		html: html,
		updateTime: Date.now(),
		createTime: createTime,
	};
};
exports.install = install;

function install(m, r) {
	return {
		prefix: "/banner",
		get: {
			"/all": [{
				des: "获取横幅列表"
			}, function*() {
				this.body = yield Banner.find({}).toArray();
			}]
		},
		post: {
			"/create": [{
				des: "增加一条横幅",
				params: [{
					name: "title",
					des: "主要的文字描述",
					type: "<form>string",
				}, {
					name: "description",
					des: "次要的文字描述",
					type: "<form>string",
				}, {
					name: "url",
					des: "普通Banner使用图片",
					type: "<form>string",
				}, {
					name: "html",
					des: "特殊的Banner需要使用HTML作为内容的时候使用这个字段",
					type: "<form>string",
				}],
				emit_with: ["form", "session"]
			}, function*() {
				const admin = yield this.admin_loginer();
				const form = this.form;

				yield Banner.insertOne(formatBanner(form));

				const banners = yield Banner.find({}).limit(1).sort([["createTime", -1]]).toArray();

				this.body = banners[0];
			}]
		},
		put: {
			"/update": [{
				des: "修改指定横幅",
				emit_with: ["form", "session"]
			}, function*() {
				const admin = yield this.admin_loginer();
				const form = this.form;

				const _id = form._id;
				if (!_id) {
					Throw("type", "缺少要修改的横幅编号");
				}

				const update_form = formatBanner(form);
				delete update_form.createTime;

				yield Banner.updateOne({
					_id: ["ObjectID", "@", _id]
				}, {
					$set: update_form
				});

				this.body = yield Banner.findOne({
					_id: ["ObjectID", "@", _id]
				});
			}]
		},
		delete: {
			"/remove/:banner_id": [{
				des: "管理员删除横幅",
				emit_with: ["params", "session"]
			}, function*() {
				const admin = yield this.admin_loginer();
				const banner_id = this.params.banner_id;
				if (!banner_id) {
					Throw("type", "缺少要删除的横幅编号");
				}

				this.body = yield Banner.deleteOne({
					_id: ["ObjectID", "@", banner_id]
				});
			}]
		}
	}
}